<template>
  <!-- 中控模块 - 素材发布中心 -->
  <div id="Material">
    <div class="main" style="padding:0.2rem;">
      <h1 class="titleH1">
        <div class="search-item">
          <span class="searchLabel">素材关键字：</span>
          <el-input v-model="form.materialKeyword" placeholder="请输入内容" clearable  style="width:2.3rem;"/>
        </div>
        <div class="search-item">
          <span class="searchLabel">素材类别：</span>
          <el-select v-model="form.materialType" placeholder="请选择" style="width:1.2rem;">
            <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" style="font-size:0.16rem;" />
          </el-select>
        </div>
        <div class="search-item">
          <span class="searchLabel">预发布终端类别：</span>
          <el-select v-model="form.terminalType" placeholder="请选择" style="width:1.8rem;">
            <el-option v-for="item in terminalOptions" :key="item.code" :label="item.name" :value="item.code" style="font-size:0.16rem;" />
          </el-select>
        </div>
        <div class="search-item">
          <span class="searchLabel">审批流程：</span>
          <el-select v-model="form.approveProcess" placeholder="请选择" style="width:2rem;">
            <el-option v-for="(item, index) in options2" :key="index" :label="item" :value="item" />
          </el-select>
        </div>
        <div class="search-item">
          <span class="searchLabel">素材提交时间：</span>
          <el-date-picker class="searchItem" v-model="form.submitTimeStr" type="month" placeholder="选择月" format="yyyy年MM月" value-format="yyyy年MM月" :picker-options="pickerBeginMonth" />
        </div>
        <div class="search-button">
          <el-button type="primary" @click="searchClick()">查询</el-button>
          <el-button type="primary" @click="resetClick()">重置</el-button>
        </div>
      </h1>
      <!-- <p style="margin:0.2rem 0.2rem 0;">
        <el-button type="primary" @click="terminalShow = true" :disabled="!selection.length>0">选择预发布终端</el-button>
      </p> -->
      <div class="content">
        <el-table ref="materialTable"
        :data="materialList"
        highlight-current-row
        style="width: 100%;min-height: calc(100vh - 5rem);"
        @current-change="handleSelectionChange"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="#fff">
          <!-- <el-table-column type="selection" width="50" /> -->
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column label="数据类别" width="150" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.materialType | dataFormate }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="approveProcess" label="流程审批类别" align="center" width="150" />
          <el-table-column prop="materialName" label="数据名称" align="center" :show-overflow-tooltip="true" />
          <el-table-column label="预发布终端类别" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.terminalType | terminaFormate }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="submitter" label="提交人" align="center" width="150" />
          <el-table-column prop="submitTime" label="提交时间" align="center" width="150" />
          <el-table-column label="操作" align="center" width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="buttonClick(scope.$index, scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            popper-class="DataAcquisition_fenye"
            :current-page="form.pageNum"
            background
            :page-sizes="[10, 20, 30, 40]"
            :page-size="form.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <div v-if="!terminalShow" class="main" style="border:none;">
      <p style="padding-left: 0.2rem;font-size: 0.14rem;color: #999;">注：微信公众号暂不支持文件、网页类型素材的发布 ！</p>
      <p class="terminalType">发布终端类别：
        <el-checkbox-group v-model="checkList" @change="checkboxGroup">
          <el-checkbox v-for="(item, index) in options2_2" :key="item.code" :label="item.code" :disabled="index==0&&disabled">{{ item.name }}</el-checkbox>
        </el-checkbox-group>
        <el-button type="primary" @click="onSubmit">终端发布</el-button>
      </p>
      <div class="content">
        <div v-for="(item, index) in checkTable" :key="index" class="terminal" v-show="checkList.includes(item.key)">
          <p><svg-icon icon-class="right" style="color:#516FE9;" /> {{ item.label }}</p>
          <el-table :ref="`${item.key}-ref`" :data="item.data" border style="width: 100%" @select="selections(item.key)" @selection-change="selectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="index" width="55" label="序号" align="center" />
            <el-table-column v-for="(data, key) in item.header" :key="key" :prop="data.key" :label="data.label" align="center" />
          </el-table>
        </div>
      </div>
    </div>
    <el-dialog :title="dataTitle" :visible.sync="Playvideo" center class="videoDialog" @close="closeVideo">
      <player :video-url="previewUrl" :state="Playvideo" />
    </el-dialog>
    <el-dialog :title="dataTitle" :visible.sync="Playvoice" center @close="closeVoice">
      <voice-Play :title="dataTitle" :src="previewUrl" :state="Playvoice" />
    </el-dialog>
  </div>
</template>
<script>
import player from '@/components/VideoPlay'
import VoicePlay from '@/components/VoicePlay'
export default {
  name: 'Material',
  components: { player, VoicePlay },
  data() {
    return {
      terminalOptions: [],    // 预发布终端类别
      options2_2: [],         // 发布终端类别
      options2: [],           // 审批流程
      form: {
        materialKeyword: '',  // 搜索字段
        materialType: '',     // 素材类别
        terminalType: '',     // 预发布终端类别
        submitTimeStr: '',    // 素材提交时间
        taskStatus: 'todo',   // 任务状态（固定参数）
        processState: 2,      // 审批状态（固定参数）
        approveProcess: '',   // 审批流程
        pageNum: 1,
        pageSize: 10
      },
      terminalShow: false,    // 是否展示预发布终端
      materialList: [],       // 素材列表
      total: 0,               // 分页器，数据总条目
      checkTable: [],         // 选中的终端类型
      selection: [],          // 勾选要发布的内容
      terminalList: {         // 终端列表
        wxList: [],           // 微信
        ydList: [],           // 移动服务平台
        otherList: [],        // 其他软件平台
        hardwareList: []      // 硬件终端
      },
      checkList: [],          // 终端 - 多选
      terminalForm: { 
        wxList: '',           // 微信公众号终端
        ydList: '',           // 移动服务平台终端
        otherList: '',        // 其他软件平台终端
        hardwareList: ''      // 硬件终端终端
      },
      tableIndex: '',         // 当前选中的终端
      pickerBeginMonth: {
        disabledDate(time) {
          const befor = time.getFullYear() < new Date('2019').getFullYear()
          const after = time.getTime() > Date.now()
          return befor || after // 设置早于当前年份，晚于当前时间的月份不可选择
        }
      },
      disabled: false,     // 网页、文件类型素材不能发布到微信公众号
      loading: true,
      dataTitle: '',       // 素材标题
      Playvideo: false,    // 视频
      Playvoice: false,    // 音频
      previewUrl: ''       // 素材详情url
    }
  },
  computed: {
    // 素材类别
    options1() {
      const option = [
        { label: '全部', value: '' },
        { label: '图文', value: 'news' },
        { label: '图片', value: 'image' },
        { label: '文件', value: 'file' },
        { label: '语音', value: 'voice' },
        { label: '视频', value: 'video' },
        { label: '网页', value: 'web' }
      ]
      return option
    }
  },
  created() {
    // 请求终端
    this.$api.getTerminal().then((response) => {
      if (response.data.status == 1) {
        this.terminalOptions = JSON.parse(JSON.stringify(response.data.data))
        this.options2_2 = JSON.parse(JSON.stringify(response.data.data))
        // for (const i in this.options2_2) {
          // this.checkList.push(this.options2_2[i].code)
        // }
        this.terminalOptions.unshift({ name: '全部', code: '' })
        this.form.terminalType = this.terminalOptions[0].code
        this.$api.getApproveProcess().then((response) => {
          if (response.data.status == 1) {
            this.options2 = JSON.parse(JSON.stringify(response.data.data))
            this.form.approveProcess = this.options2[0]
            // 默认搜索时间
            const pad = n => (n < 10 ? `0${n}` : n)
            const date = new Date()
            const yyyyMM = `${date.getFullYear()}年${pad(date.getMonth() + 1)}月`
            this.form.submitTimeStr = yyyyMM
            this.searchClick()
            this.getTerminalList()
          } else {
            this.$message.error(response.data.msg)
          }
        })
      } else {
        this.$message.error(response.data.msg)
      }
    })
  },
  methods: {
    // 搜索
    searchClick() {
      const obj = this.form
      this.$api.getMaterial(obj).then(response => {
        this.materialList = []
        this.loading = true
        if (response.data.status == 1) {
          setTimeout(() => {
            this.loading = false
            this.total = response.data.data.list.length
            this.materialList = response.data.data.list
          }, 0.5 * 1000);
        } else {
          setTimeout(() => {
            this.loading = false
            this.$message.error(response.data.msg)
          }, 2 * 1000);
        }
      }).catch(() => this.loading = false)
    },
    // 重置
    resetClick() {
      const pad = n => (n < 10 ? `0${n}` : n)
      const date = new Date()
      const yyyyMM = `${date.getFullYear()}年${pad(date.getMonth() + 1)}月`
      this.form = {
        materialKeyword: '',      // 搜索字段
        materialType: '',         // 素材类别
        approveProcess: this.options2[0], // 审批流程
        processState: 2,          // 审批状态（固定参数）
        taskStatus: 'todo',       // 任务状态（固定参数）
        pageNum: this.form.pageNum,
        pageSize: this.form.pageSize,
        terminalType: this.terminalOptions[0].code,  // 预发布终端类别
        submitTimeStr: yyyyMM     // 素材提交时间
      }
      this.searchClick()
    },
    // 操作
    buttonClick(index, data) {
      let key = data.materialType
      switch (key) {
        case 'news':
          sessionStorage.setItem('localRouter', '/ControlModule/materialDetails')
          sessionStorage.setItem('materialId', data.materialId)
          setTimeout(() => {
            this.$router.push('/ControlModule/materialDetails')
          }, 100);
          break;
        case 'image':
          this.$api.getDataDetails({id: data.materialId}, key).then((response) => {
            if (response.data.status == 1) {
              let file = response.data.data.mediaFile
              window.open(file.uploadUrl, '_blank')
            }
          })
          break;
        case 'file':
          this.$api.fileDownload({ id: data.materialId }).then((response) => {
            const blobUrl = window.URL.createObjectURL(response.data)
            const link = document.createElement('a')
            document.body.appendChild(link)
            link.style.display = 'none'
            link.href = blobUrl
            // 设置a标签的下载属性，设置文件名及格式，后缀名最好让后端在数据格式中返回
            link.download = data.materialName
            // 自触发click事件
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(blobUrl)
          })
          break;
        case 'web':
          this.$api.htmlListDetail({id: data.materialId}).then((response) => {
            if (response.data.status == 1) {
              let res = response.data.data.mediaWeb
              window.open(res.url, '_blank')
            }
          })
          break;
        default: // voice/vedio
          this.$api.getDataDetails({id: data.materialId}, key).then((response) => {
            if (response.data.status == 1) {
              let file = response.data.data.mediaFile
              this[`Play${key}`] = true
              this.dataTitle = file.fileName
              this.previewUrl = file.uploadUrl
            }
          })
          break;
      }
    },
    // 关闭视频
    closeVideo() {
      this.Playvideo = false
      this.dataTitle = ''
      this.previewUrl = ''
    },
    // 关闭音频
    closeVoice() {
      this.Playvoice = false
      this.dataTitle = ''
      this.previewUrl = ''
    },
    // 选中状态
    handleSelectionChange(val) {
      this.selection = [val.pid]
      let terminalArray = val.terminalType.split(',')
      this.checkList = []
      this.checkList = terminalArray
      if (val.materialType == 'web' || val.materialType == 'file') {
        this.disabled = true
      } else {
        this.disabled = false
      }
      let obj = {}
      for (let i in terminalArray) {
        let key = terminalArray[i]
        obj[key] = val[key]
      }
      this.tableSelection(obj)
      this.checkboxGroup(this.checkList)
    },
    // 改变每页数据条目数
    handleSizeChange(val) {
      this.form.pageSize = val
      this.searchClick()
    },
    // 当前第几页
    handleCurrentChange(val) {
      this.form.pageNum = val
      this.searchClick()
    },
    // 请求终端列表
    getTerminalList() {
      this.$api.getTerminalList().then((response) => {
        if (response.data.status == 1) {
          this.terminalList = response.data.data
          this.checkTableFN()
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    // 发布终端table
    checkTableFN() {
      this.checkTable = [
        {
          label: '微信公众号',
          key: 'wxList',
          header: [
            { label: '微信公众号名称', key: 'name' },
            { label: '负责人', key: 'manager' }
          ],
          data: this.terminalList.wxList
        },
        {
          label: '移动服务平台',
          key: 'ydList',
          header: [
            { label: '移动服务平台名称', key: 'name' },
            { label: '负责人', key: 'manager' }
          ],
          data: this.terminalList.ydList
        },
        {
          label: '其他软件终端',
          key: 'otherList',
          header: [
            { label: '软件终端名称', key: 'name' },
            { label: '栏目', key: 'section' },
            { label: '负责人', key: 'manager' }
          ],
          data: this.terminalList.otherList
        },
        {
          label: '硬件终端',
          key: 'hardwareList',
          header: [
            { label: '硬件终端名称', key: 'name' },
            { label: '负责人', key: 'manager' }
          ],
          data: this.terminalList.hardwareList
        }
      ]
    },
    // 终端类别
    checkboxGroup(checkbox) {
      // 将checkTable中选中后又取消勾选的终端数据，从form表单中清除
      const keyArr = Object.keys(this.terminalList)
      let terminalForm_Copy = {}
      keyArr.forEach(item => {
        if (!this.checkList.includes(item)) {
          terminalForm_Copy[item] = ''
          this.$refs[`${item}-ref`][0].clearSelection();
        } else {
          terminalForm_Copy[item] = this.terminalForm[item]
        }
      });
      this.terminalForm = {}
      this.terminalForm = terminalForm_Copy
    },
    // 选中素材的预发布终端，数据回显
    tableSelection(idList) {
      // 延时器：页面table是由数据循环创建，在dom节点未创建完成前，用$refs无法获取到dom，会导致后续的清空table与选中table方法报错
      let _this = this
      let keyArr = _this.checkList     // checkbox组件勾选中的数组, 例：['wxList', 'ydList']
      let checkTable= _this.checkTable // 终端类别下table，数据结构见checkboxGroup()方法中obj对象。
      for (let i in keyArr) {
        let key = `${keyArr[i]}-ref`
        this.terminalForm[keyArr[i]] = idList[keyArr[i]]
        let idArr = idList[keyArr[i]].split(',') // 从素材中获取的id是'1,2,2'形式，格式化成['1','2','2']
        _this.$refs[key][0].clearSelection();    // 清空ref值为变量key的table中的选中状态
        // 在数组checkTable中寻找，与变量key的值相等的对象
        for (let j in checkTable) {
          if (keyArr[i] == checkTable[j].key) {
            // 将该对象中的data数组中，与素材中获取的终端id匹配
            for (let k in checkTable[j].data) {
              let id = JSON.stringify(checkTable[j].data[k].id)
              // data数组中，数据id存在于idArr中的，将此条数据用element ui table的方法，完成选中效果
              if (idArr.includes(id)) {
                _this.$refs[key][0].toggleRowSelection(checkTable[j].data[k]);
              }
            }
          }
        }
      }
    },
    // 当前点击的终端类型
    selections(key) {
      this.tableIndex = key
    },
    // 当前点击终端中选中的终端
    selectionChange(data) {
      // 需上方的selections方法中this.tableIndex变量赋值成功后，再执行下方代码
      // 否则无法将选中数据赋值给数组中具体条目中的属性
      setTimeout(() => {
        const arr = []
        for (const i in data) {
          arr.push(data[i].id)
        }
        // 将勾选的终端格式化为字符串，并以‘ ，’隔开
        this.terminalForm[this.tableIndex] = arr.join(',')
      }, 500)
    },
    // 保存/提交终端发布
    onSubmit() {
      const checkList = this.checkList
      let num = false
      if (this.selection.length > 0) {
        for (let i = 0; i < checkList.length; i++) {
          const key = checkList[i]
          if (this.terminalForm[key] == '') {
            num = false
            break;
          } else {
            num = true
          }
        }
        if (num) {
          const obj = {}
          obj.pid = this.selection[0]
          obj.terminalType = this.checkList
          // 将勾选的终端类型格式化为字符串，并以‘ ，’隔开
          if (obj.terminalType.length == 1) {
            let key = obj.terminalType[0]
            obj.terminalType = key
            obj[key] = this.terminalForm[key]
          } else {
            for (const i in obj.terminalType) {
              const key = obj.terminalType[i]
              obj[key] = this.terminalForm[key]
            }
            obj.terminalType = obj.terminalType.join(',')
          }
          this.$api.submitMaterial(obj).then((response) => {
            if (response.data.status == 1) {
              this.$message.success(response.data.msg)
              location.reload()
            }
          })
        } else {
          this.$message.error('请选择需发布的终端 !')
        }
      } else {
        return this.$message.error('请选择需发布的素材 !')
      }
    }
  }
}
</script>
<style lang="scss" scoped>
#Material {
  width: 100%;
  background: #fff;
  box-shadow: #ccc 0 0 10px 0px;
  border-radius: 0.05rem;
  >>>*{ font-size: 0.16rem}
  .main {
    position: relative;
    .titleH1 {
      width: 100%;
      min-height: 0.55rem;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      font-size: 0.18rem;
      margin: 0;
      font-weight: normal;
      background: #fff;
      .search-item,
      .search-button {
        display: flex;
        justify-content: start;
        align-items: center;
        // min-width: 32%;
        margin: 0.1rem 0.15rem;
      }
      .search-item {
        .searchLabel {
          font-size: 0.16rem;
          text-align: right;
          display: inline-block;
          min-width: 1rem;
        }
        .searchItem {
          width: 1.8rem;
        }
      }
      .search-button {
        width:100%;
        justify-content: center;
      }
    }
    .terminalType {
      width: 100%;
      padding: 0 0.2rem;
      >>>.el-checkbox-group {
        width: 40%;
        display: inline-block;
      }
    }
    .content {
      padding: 0.2rem;
      min-height: 5rem;
      border-bottom: 1px solid #ccc;
      position: relative;
      overflow: hidden;
      .terminal {
        background: #F8F8F8;
        padding: 0.1rem 0.2rem;
        min-height: 2rem;
      }
      .pagination {
        width: 100%;
        background: #fff;
        text-align: right;
        padding-top: 0.2rem;
      }
    }
    .flex-column {
      display: flex;
      flex-flow: column;
    }
    .flex {
      display: flex;
    }
  }
}
</style>
